<template>
  <el-dialog
    :title="title"
    v-model="open"
    :close-on-click-modal="false"
    width="70%"
    append-to-body
  >
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
    <el-form-item label="ERP订单编号" prop="erpOrderNo">
        <el-input
          v-model="queryParams.erpOrderNo"
          placeholder="请输入ERP订单编号"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="prodName">
        <el-input
          v-model="queryParams.prodName"
          placeholder="请输入产品名称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料名称" prop="matName">
        <el-input
          v-model="queryParams.matName"
          placeholder="请输入物料名称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="批次号" prop="batchNo">
        <el-input
          v-model="queryParams.batchNo"
          placeholder="请输入批次号"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="线边仓" prop="storehouseCode">
        <el-select
          v-model="queryParams.storehouseCode"
          clearable
          filterable
          style="width: 200px"
        >
          <el-option
            v-for="(item, index) in storehouseList"
            :key="index"
            :value="item.storehouseCode"
            :label="item.storehouseName"
          >
            <span>{{ item.storehouseName }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="物料批号" prop="batchNo">
        <el-input
          v-model="queryParams.batchNo"
          placeholder="请输入物料批号"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="物料编号" prop="matCode">
        <el-input
          v-model="queryParams.matCode"
          placeholder="请输入物料编号"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
     
      <!-- <el-form-item label="物料类别" prop="type">
        <el-input
          v-model="queryParams.type"
          placeholder="请选择物料类别"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <div class="flex gap-2"  v-if="multiple" style="margin-bottom: 10px;max-height: 60px;overflow-y: auto;">
      <el-tag @close="tagClose(tag)" v-for="tag in arrInfoSelection" :key="tag.matName" closable  style="margin-right: 5px; margin-top: 5px;">
        {{ tag.matName }}
      </el-tag>
    </div>
    <el-table
      v-loading="loading"
      :data="tableData"
      maxHeight="425px"
      ref='matDialog'
      border
      show-overflow-tooltip
      @select="handleSelectionChange"
      @select-all="selectAll"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column width="150" label="ERP订单编号" align="center" prop="erpOrderNo" />
      <el-table-column label="产品名称" prop="prodName" width="150">  
      </el-table-column>
      <el-table-column label="产品编号" prop="prodNo" width="150">
      </el-table-column>
      <el-table-column label="物料编号" align="center" prop="matCode">
      </el-table-column>

      <el-table-column label="物料名称" align="center" prop="matName" />
      <el-table-column label="批次号" align="center" prop="batchNo" />
      <el-table-column label="线边仓" align="center" prop="storehouseName" />

      <el-table-column label="库位" align="center" prop="binName" />
      <!-- <el-table-column label="库存" align="center" prop="num" /> -->
      <el-table-column label="可用库存" align="center" prop="availableNum" />
      <el-table-column label="单位" align="center" prop="packageUnit" />
      <!-- <el-table-column label="规格" align="center" prop="packing" /> -->
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="">
import { listStock } from "@/api/warehouse/stock";
import { toRefs,watch,ref,reactive,nextTick ,getCurrentInstance} from "vue";
import { listStorehouse } from "@/api/storehouse/storehouse";
import {floatSub} from "@/utils/mathCount"
const props = defineProps(["factory", "line", "workshop", "section",'matType','chioseList']);
const { proxy } = getCurrentInstance();
const open = defineModel();
const loading = ref(true);
const showSearch = ref(true);
const tableData = ref([]);
const ids = ref([]);
const storehouseList = ref([]);
const single = ref(true);
const multiple = ref(true);
const selectData = ref([]);
const arrInfoSelection = ref([])
const total = ref(0);
const title = ref("");
const matDialog = ref(null)
const queryRef = ref("queryRef");
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    equipNo: undefined,
    name: undefined,
    status: undefined,
  },
});

const { queryParams } = toRefs(data);
const { factory, workshop, line, section ,matType,chioseList} = toRefs(props);
// watch(
//   () => props,
//   (newValue, oldValue) => {
//     getStorehouseList();
//   },
//   { deep: true }
// );
// watch(
//   () => showSearch.value,
//   (newValue, oldValue) => {
//     if (newValue) {
//       getStorehouseList();
//     }
//   }
// );
watch(
  () => open.value,
  (newValue, oldValue) => {
    console.log(oldValue);
    if (newValue) {
      getStorehouseList();
      getList();
    }
    // 多次进来回显
    if (newValue == true && chioseList.value && chioseList.value.length > 0) {
        arrInfoSelection.value = chioseList.value;
      }
  }
);
const emit = defineEmits(["change"]);
function getStorehouseList() {
  listStorehouse({
    factoryCode: factory.value,
    workshopCode: workshop.value,
    lineCode: line.value,
    sectionCode: section.value,
    pageNum: 1,
    pageSize: 1000,
  }).then((res) => {
    storehouseList.value = res.rows;
  });
}
/** 查询字典类型列表 */
function getList() {
  loading.value = true;
  queryParams.value.factoryCode = factory.value;
  queryParams.value.workshopCode = workshop.value;
  queryParams.value.lineCode = line.value;
  queryParams.value.sectionCode = section.value;
  queryParams.value.matType = 'mat';
  // 有的地方不需要传这个字段
  if(matType.value){
    queryParams.value.matType = ''
  }
  listStock(queryParams.value).then((response) => {
    tableData.value = response.rows;
    if(tableData.value.length ){
      tableData.value.forEach((item) => {
        item.availableNum = floatSub(item.num,item.frozenNum)
      });
    }
    console.log(arrInfoSelection.value);
    if(arrInfoSelection.value && arrInfoSelection.value.length){
      const chioseID = []
      arrInfoSelection.value.forEach(i=>{
        chioseID.push(i.erpOrderNo+i.prodNo+i.matCode+i.batchNo+i.storehouseCode+i.binCode)
      })
      nextTick(() => {
        if (tableData.value.length && arrInfoSelection.value.length) {
          tableData.value.forEach((item) => {
            const id = item.erpOrderNo+item.prodNo+item.matCode+item.batchNo+item.storehouseCode+item.binCode
            if (chioseID.includes(id)) {
              matDialog.value.toggleRowSelection(item, true);
            } else {
              matDialog.value.toggleRowSelection(item, false);
            }
            
          });
        }
      });
    }

    total.value = response.total;
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  // dateRange.value = [];
  queryRef.value.resetFields();
  handleQuery();
}
function tagClose(tag){
  const removeId = tag.erpOrderNo+tag.prodNo+tag.matCode+tag.batchNo+tag.storehouseCode+tag.binCode
  arrInfoSelection.value = arrInfoSelection.value.filter(item=>item.erpOrderNo+item.prodNo+item.matCode+item.batchNo+item.storehouseCode+item.binCode!=removeId)
  // 删除之后把表格中的勾选 去掉
  if(tableData.value.length){
    tableData.value.forEach(item=>{
      const chioseID = []
      arrInfoSelection.value.forEach(i=>{
        chioseID.push(i.erpOrderNo+i.prodNo+i.matCode+i.batchNo+i.storehouseCode+i.binCode)
      })
      const id = item.erpOrderNo+item.prodNo+item.matCode+item.batchNo+item.storehouseCode+item.binCode
      if(chioseID.includes(id)){
        matDialog.value.toggleRowSelection(item, true);
      } else{
        matDialog.value.toggleRowSelection(item, false);
      }
    })
  }

}
/** 多选框选中数据 */
function handleSelectionChange(selection, row) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  // multiple.value = !selection.length;
  // selectData.value = selection;

  let selected = selection.length && selection.indexOf(row) !== -1;
  if (selected) {
    arrInfoSelection.value.push(row);
  } else {
    arrInfoSelection.value = arrInfoSelection.value.filter((item) => item.id != row.id);
  }

}
// 全选 或全不选
function selectAll(section) {
  if (section.length) {
    // 全选  push
    section.forEach((item) => {
      arrInfoSelection.value.push(item);
    });
  } else {
    // 全不选  当页数据  删除
    if (tableData.value.length && arrInfoSelection.value.length) {
      tableData.value.forEach((item) => {
        arrInfoSelection.value = arrInfoSelection.value.filter((info) => item.id != info.id);
      });
    }
  }
  arrInfoSelection.value = uniqueObjects(arrInfoSelection.value);
}
// 数组对象去重
function uniqueObjects(arr) {
  const seen = new Map();
  return arr.filter((item) => {
    // 将对象转换为字符串（或其他可以唯一表示对象的内容）
    const key = JSON.stringify(item);
    // 如果 Map 中还没有这个键，则添加它并返回 true
    if (!seen.has(key)) {
      seen.set(key, item);
      return true;
    }
    // 如果已经有了，就返回 false，表示这个对象应该被过滤掉
    return false;
  });
}
function submitForm() {
  // open.value = false;
  // console.log("selected", selectData.value);
  // emit("change", selectData.value);
  if (arrInfoSelection.value?.length && arrInfoSelection.value.length > 0) {
    open.value = false;
    emit("change", JSON.parse(JSON.stringify(arrInfoSelection.value)));
  } else {
    proxy.$modal.msgError("请选择至少一条数据！");
  }
}

// getList();
</script>

<style lang="scss" scoped></style>
